package thingapi

import (
	"fmt"

	"github.com/gin-gonic/gin"
	socketio "github.com/googollee/go-socket.io"
)

var server *socketio.Server

//BeginMsgSocketIO 开始ws
func BeginMsgSocketIO(router *gin.Engine) {
	server, _ = socketio.NewServer(nil)
	server.OnConnect("/", func(s socketio.Conn) error {
		s.SetContext("")
		//fmt.Println("******6666*************@@@@@@@@@@connected:", s.ID())
		s.Join("alarmRoom")
		s.Join("eventRoom")
		return nil
	})

	server.OnEvent("/", "notice", func(s socketio.Conn, msg string) {
		fmt.Println("notice:", msg)
		s.Emit("reply", "have "+msg)
	})

	server.OnEvent("/chat", "msg", func(s socketio.Conn, msg string) string {
		s.SetContext(msg)
		return "recv " + msg
	})

	server.OnEvent("/", "bye", func(s socketio.Conn) string {
		last := s.Context().(string)
		s.Emit("bye", last)
		s.Close()
		return last
	})

	server.OnError("/", func(s socketio.Conn, e error) {
		fmt.Println("meet error:", e)
	})

	server.OnDisconnect("/", func(s socketio.Conn, msg string) {
		fmt.Println("！！！！！！！！！！！！！！！！！！！！！！closed", msg, s.LocalAddr(), s.RemoteAddr(), s.URL(), s.Rooms())
	})
	initAlarmListenner()
	initEventListenner()
	router.GET("/ws/*any", gin.WrapH(server))
	router.POST("/ws/*any", gin.WrapH(server))
	go func() {
		fmt.Println("begin----------------------")
		server.Serve()
		fmt.Println("begin----------------------end")
		defer server.Close()
	}()

}
